using RabbitMQ.Client;
using System;
using System.Collections;
using System.Text;
namespace RabbitMQ.Gateway.Converter
{
	public class StringToMessageConverter : IConvertToMessage
	{
		public const string _defaultCharSet = "utf-8";
		public string CharSet
		{
			get;
			set;
		}

		public StringToMessageConverter()
		{
			this.CharSet = "utf-8";
		}

		public virtual Message ConvertObjectToMessage(IModel channel, object packetToSend)
		{
            IBasicProperties basicProperties = channel.CreateBasicProperties();
            byte[] bytes;
            if (packetToSend is string)
            {
                bytes = System.Text.Encoding.GetEncoding(this.CharSet).GetBytes((string)packetToSend);
                basicProperties.ContentType = Const.PLAIN_TEXT;
            }
            else if (packetToSend is byte[])
            {
                bytes = (byte[])packetToSend;
                basicProperties.ContentType = Const.PlAIN_OBJ;
            }
            else
            {
                throw new System.ApplicationException("paketToSend has to be a string or byte[] to convert to a Message using this converter");
            }
            if (channel == null)
			{
				throw new System.ApplicationException("The channel is null, a valid channel is required to create a message");
			}
			
			basicProperties.Headers = new System.Collections.Hashtable();
            //IBasicProperties basicProperties = channel.CreateBasicProperties();
            //basicProperties.ContentType = StringToMessageConverter.PLAIN_TEXT;
			basicProperties.ContentEncoding = this.CharSet;
			return new Message
			{
				Body = bytes,
				Properties = basicProperties,
				RoutingKey = string.Empty
			};
		}
	}
}
